//
//  ImgCache.m
//  Koina
//
//  Created by welldone on 13-10-15.
//  Copyright (c) 2013年 net.koina. All rights reserved.
//

#import "ImgCache.h"

@interface ImgCache ()

@end

@implementation ImgCache

+(NSString*)getCacheDirectory{

    NSArray* paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
	NSString *cacheDirectory = [paths objectAtIndex:0];
	cacheDirectory = [cacheDirectory stringByAppendingPathComponent:@"KoinaImgCaches"];
    
    BOOL isDir = YES;
    	if (![[NSFileManager defaultManager] fileExistsAtPath:cacheDirectory isDirectory:&isDir]) {
    		[[NSFileManager defaultManager] createDirectoryAtPath:cacheDirectory withIntermediateDirectories:NO attributes:nil error:nil];
    	}
    
	return cacheDirectory;
}





+(NSString*)getTempDirectory{
    
    NSArray* paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
	NSString *cacheDirectory = [paths objectAtIndex:0];
	cacheDirectory = [cacheDirectory stringByAppendingPathComponent:@"TempKoinaImgCaches"];
	
    BOOL isDir = YES;
    if (![[NSFileManager defaultManager] fileExistsAtPath:cacheDirectory isDirectory:&isDir]) {
        [[NSFileManager defaultManager] createDirectoryAtPath:cacheDirectory withIntermediateDirectories:NO attributes:nil error:nil];
    }
    
	return cacheDirectory;
}



//无条件清空所有的
+(void)cleanAll{
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        NSFileManager *fileManager = [NSFileManager defaultManager];
        
        [fileManager removeItemAtPath:[self getCacheDirectory] error:nil];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
        });
    });
}




//重新设置缓存，条件清空
+ (void)resetCache{
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        NSFileManager *fileManager = [NSFileManager defaultManager];
        NSError *error = nil;
        
        //清除图片缓存
        //fileList便是包含有该文件夹下所有文件的文件名及文件夹名的数组
        NSArray *fileList = [fileManager contentsOfDirectoryAtPath:[self getCacheDirectory] error:&error];
        if (fileList!=nil) {
            
            NSMutableString *path = [[NSMutableString alloc]init];
            NSMutableDictionary *fileAttributes = [[NSMutableDictionary alloc]init];
            NSTimeInterval interval = 24*60*60*7;//  七天缓存期
            
            NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
            [dateformatter setDateFormat:@"YYYYMMdd"];
            
            for (NSString *fileName in fileList) {
                
                [path setString:[[self getCacheDirectory] stringByAppendingPathComponent:fileName]];
                [fileAttributes addEntriesFromDictionary:[fileManager attributesOfItemAtPath:path error:nil]];
                
                if (fileAttributes != nil&&[fileAttributes count]>0) {
                    
                    NSDate* modDate = [fileAttributes objectForKey:NSFileModificationDate];
                    modDate = [modDate initWithTimeInterval:+interval sinceDate:modDate];
                    NSString * modDataString=[dateformatter stringFromDate:modDate];
                    modDate = [dateformatter dateFromString:modDataString];
                    
                    
                    NSDate *nowData=[NSDate date];
                    NSString * locationString=[dateformatter stringFromDate:nowData];
                    nowData = [dateformatter dateFromString:locationString];

                    
                    NSLog(@"扫描到图片缓存:    %@",modDate);
                    
                    if ([modDate compare:nowData]==NSOrderedAscending) {//mod < now ?
                        [fileManager removeItemAtPath:path error:nil];
                         NSLog(@"删除过期的图片缓存------------: %@",modDate);
                    }
                }else{
                    [fileManager removeItemAtPath:path error:nil];
                }
            }
        }
        
        
        /*
        [fileManager removeItemAtPath:[self getTempDirectory] error:nil];//删除整个目录
        清除临时文件夹的图片缓存
        fileList便是包含有该文件夹下所有文件的文件名及文件夹名的数组
         */
        fileList = [fileManager contentsOfDirectoryAtPath:[self getTempDirectory] error:&error];
        if (fileList!=nil) {
            for (NSString *fileName in fileList) {
                
                NSString *path = [[self getTempDirectory] stringByAppendingPathComponent:fileName];
                NSDictionary *fileAttributes = [fileManager attributesOfItemAtPath:path error:nil];
                if (fileAttributes != nil&&[fileAttributes count]>0) {
                    
                    //  一天缓存期
                    NSDate* modDate = [fileAttributes objectForKey:NSFileModificationDate];
                    
                    NSDate *nowData=[NSDate date];
                    NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
                    [dateformatter setDateFormat:@"YYYYMMdd"];
                    
                    NSString * locationString=[dateformatter stringFromDate:nowData];
                    nowData = [dateformatter dateFromString:locationString];
                    NSLog(@"扫描到临时图片缓存:    %@",modDate);
                    if ([modDate compare:nowData]==NSOrderedAscending) {// mod < now
                        [fileManager removeItemAtPath:path error:nil];
                        NSLog(@"删除过期的临时图片缓存------------: %@",modDate);
                    }
                    
                }else{
                    [fileManager removeItemAtPath:path error:nil];
                }
            }
        }
        
        
        dispatch_async(dispatch_get_main_queue(), ^{
        });
    });
}




//从缓存中获取数据
+ (NSData*) objectForKey:(NSString*)key {
    
	NSFileManager *fileManager = [NSFileManager defaultManager];
	NSString *filename = [[[self getCacheDirectory] stringByAppendingPathComponent:key] stringByAppendingString:@""];
	
	if ([fileManager fileExistsAtPath:filename])//如果要请求的缓存数据文件存在
	{
        NSData *data = [NSData dataWithContentsOfFile:filename];
        return data;
	}
	return nil;
}



+ (void)setObject:(NSData*)data forKey:(NSString*)key{
    
    	NSFileManager *fileManager = [NSFileManager defaultManager];
    	NSString *filename = [[[self getCacheDirectory] stringByAppendingPathComponent:key] stringByAppendingString:@""];
    
        BOOL isDir = YES;
    	if (![fileManager fileExistsAtPath:[self getCacheDirectory] isDirectory:&isDir]) {
    		[fileManager createDirectoryAtPath:[self getCacheDirectory] withIntermediateDirectories:NO attributes:nil error:nil];
    	}
    
    	NSError *error;
    	@try {
    		[data writeToFile:filename options:NSDataWritingAtomic error:&error];
    	}
    	@catch (NSException * e) {
    	}

}


//把数据追加写入缓存，
+ (void) setObjectAppend:(NSData*)data forKey:(NSString*)key {
    
    
    NSString *filePath = [[self getCacheDirectory] stringByAppendingPathComponent:key];;
    if([[NSFileManager defaultManager] fileExistsAtPath:filePath] == NO){
        [[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil];
    }
    
    FILE *file = fopen([filePath UTF8String], [@"ab+" UTF8String]);
    if(file != NULL){
        fseek(file, 0, SEEK_END);
    }
    int readSize = [data length];
    fwrite((const void *)[data bytes], readSize, 1, file);
    fclose(file);
}




+ (void)setObjectToTemp:(NSData*)data forKey:(NSString*)key{
    
    NSString *filePath = [[[self getTempDirectory] stringByAppendingPathComponent:key] stringByAppendingString:@""];
    if([[NSFileManager defaultManager] fileExistsAtPath:filePath] == NO){
        [[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil];
    }
    
    NSError *error;
    @try {
        [data writeToFile:filePath options:NSDataWritingAtomic error:&error];
    }
    @catch (NSException * e) {
    }
    
}




+ (NSData*)getObjectFromTempforKey:(NSString*)key{

    NSFileManager *fileManager = [NSFileManager defaultManager];
	NSString *filename = [[[self getTempDirectory] stringByAppendingPathComponent:key] stringByAppendingString:@""];
	
	if ([fileManager fileExistsAtPath:filename])//如果要请求的缓存数据文件存在
	{
        NSData *data = [NSData dataWithContentsOfFile:filename];
        return data;
	}
	return nil;
}

@end
